import { message } from "antd";
import { CSSProperties, PropsWithChildren } from "react";
import { useDrop } from "react-dnd";
import { useComponentConfigStore } from "../../stores/component-config";
import { useComponentsStore, getComponentById } from "../../stores/components";
import { type ItemType } from "@editor/hooks/useMaterialDrop";

export interface CommonComponentProps extends PropsWithChildren {
    id: number;
    name: string;
    styles?: CSSProperties;
    [key: string]: any;
}


function Page({ children, id, styles }: CommonComponentProps) {
    const { addComponent, deleteComponent, components } = useComponentsStore();
    const { componentConfig } = useComponentConfigStore();
    const [{ canDrop }, drop] = useDrop(() => ({
        accept: ['Button', 'Container', 'Input', 'Modal', 'Table', 'Form'], // 指定接收的 type
        drop: (item: ItemType, monitor) => { // drop成功的回调
            message.success(item.type);
            if (monitor.didDrop()) return;
            if (item.dragType === 'move') {
                const component = getComponentById(item.id!, components)!;
                deleteComponent(item.id!);
                addComponent(component, id);
            } else {
                const config = componentConfig[item.type];
                addComponent({
                    id: new Date().getTime(),
                    name: item.type,
                    props: config.defaultProps,
                    desc: config.desc,
                    styles: {
                        // backgroundColor: 'green'
                    }
                }, id)
            }
        },
        collect: (monitor) => ({ // 采集drop过程中的状态，并返回
            canDrop: monitor.canDrop()
        })
    }))

    return (
        <div ref={drop} data-component-id={id} className="p-[20px] h-[100%] box-border" style={{ ...styles, border: canDrop ? '2px solid blue' : 'none' }}>
            {children}
        </div>
    )
}

export default Page;